<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-23 11:41:29
 * @LastEditTime: 2025-01-26 17:18:51
 * @FilePath: /env-manager-pc/src/views/update/manager/index.vue
-->
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import edit from './edit.vue'
import type { updateForm } from './page'
import type { doLoading } from '@/types/page'
import { useEnvOrgs, useOwnerOrgs, useUpdateStates } from '@/utils/dataHook'
import { usePage } from '@/utils/commonHook'
import updateApi from '@/api/modules/update'

const router = useRouter()
const editRef = ref()
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)
const searchData = reactive({
  'DIM.Devices.Filters.AssetCodeFilter': '',
  'DIM.Devices.Filters.OwnerOrgGUIDFilter': '',
  'DIM.Business.DeviceFilters.EntNameFilter': '',
  'DIM.GYHR.DeviceFilters.UpgradeState': [],
  'DIM.GYHR.DeviceFilters.UpgradeVer': [],
  'DIM.Business.Envs.DeviceFilters.EnvOrgGUIDFilter': '',
})
const tableData = ref<any[]>([])
const loading = ref(false)
const tableRef = ref()

async function getTableData() {
  loading.value = true
  const res = await updateApi.GetLastUpgrades({
    objFilter: {
      Type: 'DIM.FilterCollection',
      LogicOperator: 0,
      Filters: [
        {
          Type: 'DIM.Business.DeviceFilters.EntNameFilter',
          Value: [searchData['DIM.Business.DeviceFilters.EntNameFilter']],
        },
        {
          Type: 'DIM.Devices.Filters.AssetCodeFilter',
          IsFuzzy: true,
          Value: [searchData['DIM.Devices.Filters.AssetCodeFilter']],
        },
        {
          Type: 'DIM.GYHR.DeviceFilters.UpgradeState',
          Values: searchData['DIM.GYHR.DeviceFilters.UpgradeState'], // 升级状态ID
        },
        {
          Type: 'DIM.Devices.Filters.OwnerOrgGUIDFilter',
          Value: [searchData['DIM.Devices.Filters.OwnerOrgGUIDFilter']],
        },

        {
          Type: 'DIM.GYHR.DeviceFilters.UpgradeVer',
          FilterKey: 'Befour',
          Values: searchData['DIM.GYHR.DeviceFilters.UpgradeVer'],
        },
        {
          Type: 'DIM.Business.Envs.DeviceFilters.EnvOrgGUIDFilter',
          Value: [searchData['DIM.Business.Envs.DeviceFilters.EnvOrgGUIDFilter']],
        },
      ],
    },
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Rows, RecordsetCount } = res
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

getTableData()

function search() {
  page.PageNum = 1
  getTableData()
}

const OwnerList = useOwnerOrgs()
const envOrgs = useEnvOrgs()
const updateStates = useUpdateStates()

const versionList = ref<any>([])
updateApi.GetUpgradeFiles({ name: '', ver: '', pageNum: 1, pageSize: 9999 }).then((res) => {
  versionList.value = res.Objs
})
const defaultProps = {
  children: 'Children',
  label: 'Name',
}

function toEnt(row: any) {
  router.push(`/document/manager/modify/${row.EntObjID}`)
}

function toUpdate() {
  const rows = tableRef.value.getCheckboxRecords()
  if (rows.length <= 0) {
    return ElMessage.warning('请勾选数据')
  }
  editRef.value.open({})
}

async function submitData(formData: updateForm, doLoading: doLoading) {
  try {
    doLoading(true)
    const rows = tableRef.value.getCheckboxRecords()
    const res = await updateApi.StartUpgrades({
      fileID: formData.fileID,
      deviceObjIDs: rows.map((item: any) => item.DeviceObjID),
    })
    doLoading(false)
    editRef.value.close()
    Object.keys(res).forEach((id: string) => {
      const row = tableData.value.find((item: any) => item.DeviceObjID === id)
      if (row) {
        row.UpgradeState = res[id]
      }
    })
  }
  catch (e) {
    doLoading(false)
  }
}
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol :span="6">
              <ElFormItem label="企业名称">
                <ElInput v-model="searchData['DIM.Business.DeviceFilters.EntNameFilter']" clearable placeholder="请输入" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="设备编码">
                <ElInput v-model="searchData['DIM.Devices.Filters.AssetCodeFilter']" clearable placeholder="请输入" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="升级状态">
                <ElSelect v-model="searchData['DIM.GYHR.DeviceFilters.UpgradeState']" class="w-full" clearable multiple placeholder="请选择">
                  <ElOption v-for="item in updateStates" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="运维公司">
                <el-tree-select
                  v-model="searchData['DIM.Devices.Filters.OwnerOrgGUIDFilter']"
                  value-key="Code"
                  class="w-full"
                  :data="OwnerList"

                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable check-strictly
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="升级前版本号">
                <ElSelect v-model="searchData['DIM.GYHR.DeviceFilters.UpgradeVer']" class="w-full" multiple clearable filterable placeholder="请选择">
                  <ElOption v-for="item in versionList" :key="item.Ver" :label="item.Ver" :value="item.Ver" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="管理机构">
                <el-tree-select
                  v-model="searchData['DIM.Business.Envs.DeviceFilters.EnvOrgGUIDFilter']"
                  value-key="Code"
                  :data="envOrgs"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="6" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
              <ElButton type="success" @click="toUpdate">
                升级
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table
          ref="tableRef"
          height="100%" auto-resize
          border
          :data="tableData"
          :loading="loading"
          :row-config="{ isCurrent: true }"
        >
          <VxeColumn title="" type="checkbox" width="80" />
          <VxeColumn title="序号" type="seq" width="80" />
          <!-- <VxeColumn field="OwnerOrgClassifyName" title="类型" min-width="100" /> -->
          <VxeColumn field="OwnerOrgName" title="运维公司" min-width="100" show-overflow />
          <VxeColumn field="EnvOrgName" title="管理机构" min-width="100" show-overflow />
          <VxeColumn field="EntName" title="企业名称" min-width="220" show-overflow>
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click="toEnt(row)"
              >
                {{ row.EntName }}
              </el-button>
            </template>
          </VxeColumn>
          <VxeColumn field="DeviceName" title="设备名称" min-width="220" show-overflow />
          <VxeColumn field="DeviceAsset" title="设备编码" min-width="220" />
          <VxeColumn field="UpgradeState" title="升级状态" width="120" show-overflow />
          <VxeColumn field="UpBefourVer" title="升级前版本号" width="130" show-overflow />
          <VxeColumn field="UpEndVer" title="升级后版本号" width="130" show-overflow />
          <VxeColumn field="UpLastBeginTime" title="升级开始时间" width="130" />
          <VxeColumn field="UpLastEndTime" title="升级结束时间" width="130" />
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
    <edit ref="editRef" :version-list="versionList" @submit="submitData" />
  </div>
</template>
